package com.yupi.springbootinit.utils;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author admin
 * @date 2025/4/27
 */
public class RedisIdWorker {

    private final StringRedisTemplate stringRedisTemplate;

    private static final long BEGIN_TIMESTAMP = 1745752385L;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextId(String keyPrefix) {
        // 1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        //     2. 获取当前日期
        String dateStr = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //     3. 生成increase
        Long increment = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + dateStr);
        //     返回id
        return timestamp << 32 | increment;
    }

}
